package top.maof.mfcoin.tx;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import top.maof.mfcoin.algo.SecretUtil;

import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Objects;

/**
 * 交易输入
 * <p>
 * coinBase不用注明币的来源
 *
 * @author 毛逢
 * @date 2021/11/11 11:16
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Input {

    private String address;

    private int coin;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Input input = (Input) o;
        return coin == input.getCoin() &&
                address.equals(input.getAddress());

    }


    public static byte[] hashInput(Input in) {

        byte[] addressBytes = Base64.getDecoder().decode(in.address);
        byte[] coinBytes = Integer.toBinaryString(in.coin).getBytes();

        byte[] inBytes = new byte[addressBytes.length + coinBytes.length];

        System.arraycopy(addressBytes, 0, inBytes, 0, addressBytes.length);

        System.arraycopy(coinBytes, 0, inBytes, addressBytes.length, coinBytes.length);


        byte[] digest = null;
        try {
            digest = SecretUtil.digest(SecretUtil.DIGEST_ALGORITHM_SHA256, inBytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return digest;
    }

    public static String hashBase64(Input in) {
        return Base64.getEncoder().encodeToString(hashInput(in));
    }
}
